package com.lagouedu.filter;

import com.lagouedu.service.TokenFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
public class TokenFilter implements GlobalFilter, Ordered {


    @Autowired
    private TokenFeign tokenFeign;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        if(path.contains("/register") || path.contains("/login")|| path.contains("/code")|| path.contains("/email") || path.contains("/isRegistered")){
            // 对于用户微服务和邮件微服务直接放行
            return chain.filter(exchange);
        }
        // 对 token进行验证
        List<String> token = request.getHeaders().get("token");
        if(token == null || token.size() ==0){
            R r1 = R.error("token校验失败").put("code", 303);
            DataBuffer wrap = response.bufferFactory().wrap(r1.toString().getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        R r = tokenFeign.getEmailByToken(token.get(0));
        if(r!= null && ((int)r.get("code"))==200){
            // 放行
            return chain.filter(exchange);
        }
        R r1 = R.error("token校验失败").put("code", 303);
        DataBuffer wrap = response.bufferFactory().wrap(r1.toString().getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
